package controller_statistics

import (
	"tools-api/src/common/utils"
	"tools-api/src/jcj/service/service_book"
	"tools-api/src/jcj/service/service_statistics"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"

	"github.com/gin-gonic/gin"
)

// GetBillList 年账单/月账单
// type 账单类型
// - 1 年账单
// - 2 月账单
func GetBillList(ctx *gin.Context) {
	_type := utils.Str2Int(ctx.Query("type"))
	if _type != 1 && _type != 2 {
		response.Fail(ctx, "参数错误")
		return
	}
	year := utils.Str2Int(ctx.Query("year"))
	if _type == 2 && year <= 0 {
		response.Fail(ctx, "请选择账单年份")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	list := service_statistics.GetBillList(uuid, book, _type, year, book.MonthStart)
	response.Success(ctx, list)
}

// GetBillAccountList 年账单/月账单  按收支账户统计
// type 账单类型
// - 1 年账单
// - 2 月账单
func GetBillAccountList(ctx *gin.Context) {
	_type := utils.Str2Int(ctx.Query("type"))
	if _type != 1 && _type != 2 {
		response.Fail(ctx, "参数错误")
		return
	}
	accountId := utils.Str2Int64(ctx.Query("account_id"))
	if accountId < 0 {
		response.Fail(ctx, "请选择收支账户")
		return
	}
	year := utils.Str2Int(ctx.Query("year"))
	if _type == 2 && year <= 0 {
		response.Fail(ctx, "请选择账单年份")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	account := service_book.GetAccountById(accountId)
	if account.Id < 0 { // 账户不正确
		response.Fail(ctx, "参数错误")
		return
	}
	list := service_statistics.GetBillListByAccount(uuid, book, account, _type, year)
	response.Success(ctx, list)
}

// GetBillDailyList 获取每日收支
func GetBillDailyList(ctx *gin.Context) {
	start := ctx.Query("start")
	end := ctx.Query("end")
	if start == "" || end == "" {
		response.Fail(ctx, "参数错误")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	result := service_statistics.GetBillDailyInfos(uuid, book.Id, start, end)
	response.Success(ctx, result)
}

// GetBillDetailByTypes 类别排行榜明细
func GetBillDetailByTypes(ctx *gin.Context) {
	start := ctx.Query("start")
	end := ctx.Query("end")
	typesId := utils.Str2Int64(ctx.Query("id"))
	if start == "" || end == "" || typesId <= 0 {
		response.Fail(ctx, "参数错误")
		return
	}
	uuid := request.GetCurrentUser(ctx)
	book := service_book.GetCurrentBook(uuid)
	if book.Id == 0 {
		response.Fail(ctx, "请选择当前账本")
		return
	}
	list := service_statistics.GetBillDetailByTypes(uuid, book.Id, typesId, start, end)
	response.Success(ctx, list)
}
